"""
简历相关API
简历上传、查询等功能
"""
from flask import Blueprint, request, jsonify
from utils.file_utils import FileUtils
from resume_processor import ResumeProcessor
from config import Config

resume_bp = Blueprint('resume', __name__, url_prefix='/api')

@resume_bp.route('/upload', methods=['POST'])
def upload_resume():
    try:
        print("\n=== 收到上传请求 ===")
        print("请求头:", request.headers)
        
        if 'file' not in request.files:
            print("错误: 请求中未包含文件部分")
            return jsonify({'error': 'No file part'}), 400
            
        file = request.files['file']
        print(f"文件信息 - 文件名: {file.filename}, 类型: {file.content_type}")
        
        if file.filename == '':
            print("错误: 未选择文件")
            return jsonify({'error': 'No selected file'}), 400
        
        # 读取文件内容并重置指针
        file_data = file.read()
        print(f"文件大小: {len(file_data)} bytes")
        file.seek(0)
        
        if not FileUtils.allowed_file(file.filename):
            allowed = ', '.join(Config.ALLOWED_EXTENSIONS)
            file_ext = file.filename.split('.')[-1].lower() if '.' in file.filename else None
            print(f"错误: 不允许的文件类型. 允许类型: {allowed}, 收到类型: {file_ext}")
            return jsonify({
                'error': 'File type not allowed',
                'allowed_types': allowed,
                'received_type': file_ext
            }), 400

        print("文件验证通过，开始保存...")
        filename = FileUtils.generate_filename(file.filename)
        save_path = FileUtils.save_file(file, filename)
        print(f"文件保存成功: {save_path}")

        # 处理简历
        try:
            print(f"开始处理简历文件: {save_path}")
            processor = ResumeProcessor()
            resume_data = processor.process_resume(save_path)
            print("简历处理完成")
        except Exception as e:
            print(f"简历处理失败: {str(e)}")
            import traceback
            traceback.print_exc()
            raise
        
        return jsonify({
            'message': '上传成功',
            'filename': filename,
            'resume_data': resume_data
        }), 201

    except Exception as e:
        print(f"上传处理异常: {str(e)}")
        return jsonify({'error': f'服务器内部错误: {str(e)}'}), 500

@resume_bp.route('/resumes/latest', methods=['GET'])
def get_latest_resume():
    # 这里只做示例，实际应查数据库
    import os
    files = sorted([f for f in os.listdir('uploads') if FileUtils.allowed_file(f)], reverse=True)
    if not files:
        return jsonify({'error': 'No resumes found'}), 404
    filename = files[0]
    return jsonify({'filename': filename})
